package com.yanshaohui.springboot.pinyin;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

//汉子转拼音，并分词
public class Chinese {
	
	private HanyuPinyinOutputFormat format = null;
	private String[] pinyin;

	public Chinese() {
		format = new HanyuPinyinOutputFormat();
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		pinyin = null;
	}

	// 转换单个中文字符
	public String getCharacterPinYin(char c) {
		try {
			pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}

		// 如果c不是汉字，返回null
		if (null == pinyin || pinyin.length==0){
			return null;
		}
		
		// 多音字取第一个值
		return pinyin[0];
	}

	// 转换一个字符串
	public String getStringPinYin(String str) {
		StringBuilder sb = new StringBuilder();

		int length = str.length();
		String tmp = null;
		for (int i = 0; i < length; i++) {
			if(tmp != null){
				sb.append("\'");
				tmp = getCharacterPinYin(str.charAt(i));
			}else{
				tmp = getCharacterPinYin(str.charAt(i));
				if(tmp!=null && i>0){
					sb.append("\'");
				}
			}
			
			if (null == tmp) {
				// 如果str.charAt(i)不是汉字，则保持原样
				sb.append(str.charAt(i));
			} else {
				sb.append(tmp);
			}
		}
		return sb.toString().trim();
	}
}